package com.qxzn.app.util;

import android.util.Log;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolManager {

    private static ThreadPoolManager mThreadPoolManager;

    //核心线程数
    private int mCorePoolSize;
    //最大线程数
    private int mMaxPoolSize;
    //存活时间
    private long mKeptAliveTime = 1;
    private TimeUnit mTimeUnit = TimeUnit.HOURS;

    private ThreadPoolExecutor mExecutor;

    public static ThreadPoolManager getInstance(){
        if (mThreadPoolManager == null){
            synchronized (ThreadPoolManager.class){
                if (mThreadPoolManager == null) {
                    mThreadPoolManager = new ThreadPoolManager();
                    Log.i("ThreadPool","创建了一个线程池");
                }
            }
        }
        return mThreadPoolManager;
    }

    private ThreadPoolManager(){
        createThreadPool();
    }

    private void createThreadPool(){
        mCorePoolSize = Runtime.getRuntime().availableProcessors() * 2 + 1;
        //虽然maximumPoolSize用不到，但是需要赋值，否则报错
        mMaxPoolSize = mCorePoolSize;
        Log.i("ThreadPool","线程数："+mCorePoolSize);

        mExecutor = new ThreadPoolExecutor(
                mCorePoolSize,
                mMaxPoolSize,
                mKeptAliveTime,
                mTimeUnit,
                new LinkedBlockingQueue<Runnable>(),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );
    }

    //执行线程
    public void execute(Runnable runnable){
        if (mExecutor == null){
            createThreadPool();
        }
        if (mExecutor != null){
            mExecutor.execute(runnable);
        }
    }

    //移除线程
    public void remove(Runnable runnable){
        if (runnable != null && mExecutor != null){
            mExecutor.remove(runnable);
        }
    }
}
